//
//  Tjsp_Vc.swift
//  Pods
//
//  Created by eme on 2017/3/28.
//
//


/*
 owner:cy
 update:2017年03月28日17:27:12
 info:  推荐商品vc
 model: HpProductModel
 viewmodel: Tjsp_Vm
 */
import RxSwift
import UtilCore
import EmptyDataView
import RickonCore

class Tjsp_Vc: Empty_TVc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var product_Tv: UITableView!
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    var productId:String?
    var manageVm:Tjsp_Vm?
    var productList = [HpProductModel]() {
        didSet {
            self.product_Tv.reloadData()
        }
    }
    
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        // 下拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(Tjsp_Vc.headerRefresh))
        self.product_Tv.mj_header = header
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(Tjsp_Vc.footerRefresh))
        footer.isAutomaticallyHidden = true
        self.product_Tv.mj_footer = footer
        self.product_Tv.dzn_tv_emptyDataSource = self
        self.product_Tv.dzn_tv_emptyDelegate = self
        self.product_Tv.tableFooterView = UIView()
        ///隐藏滑动条
        self.product_Tv.showsVerticalScrollIndicator = false
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        /**
         *  初始化viewmodel
         */
        self.manageVm = Tjsp_Vm(
            input: (
                refreshTriger:  Observable.of(rx.sentMessage(#selector(Tjsp_Vc.headerRefresh)).map { _ in () }, Observable.just().map { _ in () })
                    .merge().filter{ _ in
                        self.productId != nil
                    }.map{self.productId!},
                loadMoreTriger: rx.sentMessage(#selector(Tjsp_Vc.footerRefresh)).map { _ in () }.filter{ _ in
                    self.productId != nil
                    
                    }.map{self.productId!}
        ))
        self.manageVm?
            .productsElements
            .asObservable()
            .do(onNext: {[unowned self] (_) in
                self.errorPageView.isHidden = true
            })
            .subscribe(onNext: {[unowned self] (list) in
                self.showEmptyView = true
                self.productList = list
            })
            .disposed(by: disposeBag)
        /**
         *  通过vm 的loding 显示 加载进度
         */
        self.manageVm?
            .loading.asObservable()
            .bindTo(self.view.rx_loading)
            .disposed(by: disposeBag)
        /**
         *  通过vm 的hasNextPage 配置数据是否加载完毕
         */
        self.manageVm?
            .hasNextPage.asDriver()
            .asObservable()
            .subscribe(onNext: {[unowned self] (hasNextPage) in
                if !hasNextPage {
                    self.footer.endRefreshingWithNoMoreData()
                }else {
                    /** 重置没有更多的数据（消除没有更多数据的状态） */
                    self.footer.resetNoMoreData()
                }
            })
            .disposed(by: disposeBag)
        self.manageVm?
            .error.asObserver()
            .subscribe(onNext: { [unowned self] ( error ) in
                /// 220002 表示 该数据已经过期，需要返回首页 并且刷新首页数据
                if  error.code == 220002{
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConfig.notification.netWorkSuccessKey), object: nil)
                    self.view.toastErrorCompletion(error){ _ in
                        self.navigationController?.popViewController(animated: true)
                    }
                }else{
                    self.view.toastError(error)
                }
            })
            .disposed(by: disposeBag)
//        self.manageVm?
//            .error.asObserver()
//            .bindTo(self.view.rx_error)
//            .disposed(by: disposeBag)
        self.manageVm?
            .refresherror.asObserver()
            .subscribe(onNext: { [unowned self] ( error ) in
                /// 220002 表示 该数据已经过期，需要返回首页 并且刷新首页数据
                let code = "\(error.code)"
                if code.hasPrefix("2") {
                    if  error.code == 220002{
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConfig.notification.netWorkSuccessKey), object: nil)
                        self.view.toastErrorCompletion(error){ _ in
                            self.navigationController?.popViewController(animated: true)
                        }
                    }else{
                        self.view.toastError(error)
                    }
                }else{
                    var errorMsg = "加载失败啦～点击重新加载试试"
                    /// code 小于0 一般为 没有可用的网络 ,否则 加载失败啦～点击重新加载试试
                    if error.code == -1009 {
                        errorMsg = "没有可用的网络"
                    }
                    if let emptyView = self.view.viewWithTag(UtilCore.ErrorPageViewTag) as? ErrorPageView {
                        emptyView.isHidden = false
                        emptyView.errorStr = errorMsg
                    }else{
                        self.errorPageView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
                        self.errorPageView.errorStr = errorMsg
                        self.errorPageView.isHidden = false
                        self.view.addSubview(self.errorPageView)
                    }
                }
            })
            .disposed(by: disposeBag)
        self.errorPageView
            .reloadSubject
            .bindTo(self.manageVm!.reloadTrigger)
            .disposed(by: disposeBag)
    }
}
extension Tjsp_Vc{
    // 顶部刷新
    func headerRefresh(){
        // 结束刷新
        self.product_Tv.mj_header.endRefreshing()
    }
    
    func footerRefresh(){
        self.product_Tv.mj_footer.endRefreshing()
    }
}
// MARK: UITableViewDelegate
extension Tjsp_Vc :UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.productList.count
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "Tjsp_TCell", for: indexPath)as! Tjsp_TCell
        cell.item = self.productList[indexPath.row]
        return cell
    }
    /*
     // fixed font style. use custom view (UILabel) if you want something different
     func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
     
     }
     func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?{
     
     }
     */
    
}
// MARK: UITableViewDelegate
extension Tjsp_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: true)
        let model = self.productList[indexPath.row]
        _ = "productdetail".openURL(["pdid":"\(model.pdid)"])
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 125
    }
    
}
///EmptyDelegate 空数据代理
extension Tjsp_Vc{
    override func didTap(emptyView scrollView: UIScrollView, button: UIButton){
        
    }
}
/// 空数据数据代理
extension Tjsp_Vc :EmptyDataSource{
    
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString?{
        return Theme.getEmptyDesc("未找到符合的商品～")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage?{
        return UIImage(named: "brandproduct-empty", in: RobbCore.bundle, compatibleWith: nil)
    }
    func buttonTitle(emptyView scrollView: UIScrollView, state: UIControlState) -> NSAttributedString?{
        return Theme.getEmptyButtonTitle("重新加载")
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return Theme.v.bg_color
    }
}
